package com.ruoyi.custom.service.impl;

import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.enums.UserStatus;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.custom.service.IUserService;
import com.ruoyi.system.api.RemoteUserService;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class UserService implements IUserService {
    @Autowired
    private RemoteUserService remoteUserService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private TokenService tokenService;
    private static final String SMS_CODE_KEY = "sms:code:";
    @Override
    public void register(SysUser user) {
        remoteUserService.registerUserInfo(user, SecurityConstants.INNER);
    }

    @Override
    public R<?> login(String phoneNumber, String code) {

        if (phoneNumber == null || code == null) {
            throw new ServiceException("手机号和验证码不能为空");
        }

        // 2. 校验手机号是否已注册（核心修正：用布尔值判断，不涉及 SysUser）
        R<Boolean> checkPhoneResult = remoteUserService.checkPhoneUnique(phoneNumber, SecurityConstants.INNER);
        // 先判断远程调用是否成功（如服务超时、接口异常）
        System.out.println("校验手机号结果：" + checkPhoneResult.getData());
        if (!R.isSuccess(checkPhoneResult)) {
            throw new ServiceException("校验手机号失败：" + checkPhoneResult.getMsg());
        }
        boolean isPhoneUnique = checkPhoneResult.getData();
        if (isPhoneUnique) {
            throw new ServiceException("该手机号未注册，请先完成注册");
        }
        // 走到这里，说明 isPhoneUnique=false → 手机号已注册，继续登录流程
        // 3. 从Redis获取并校验验证码
        String redisCodeKey = SMS_CODE_KEY + phoneNumber;
        String redisCode = redisTemplate.opsForValue().get(redisCodeKey);
        if (redisCode == null) {
            throw new ServiceException("验证码已过期，请重新获取");
        }
        if (!code.equals(redisCode)) {
            throw new ServiceException("验证码不正确");
        }
        R<SysUser> userResult = remoteUserService.getUserByPhone(phoneNumber, SecurityConstants.INNER);
        System.out.println("根据手机号查询用户结果：" + userResult.getData());
        // 先判断远程调用是否成功（如服务超时、接口异常）
        if (!R.isSuccess(userResult)) {
            throw new ServiceException("根据手机号查询用户失败：" + userResult.getMsg());
        }

        SysUser existUser = userResult.getData();
        System.out.println("根据手机号查询到的用户信息：" + existUser);


        R<LoginUser> loginUserResult = remoteUserService.getUserInfo(existUser.getUserName(), SecurityConstants.INNER);
        if (!R.isSuccess(loginUserResult)) {
            throw new ServiceException("获取登录信息失败：" + loginUserResult.getMsg());
        }
        LoginUser loginUser = loginUserResult.getData();
        Map<String, Object> tokenMap = tokenService.createToken(loginUser);

        // 4. 二次封装：添加用户信息到返回结果中
        Map<String, Object> resultMap = new HashMap<>(tokenMap); // 复制原有token信息

        // 构建用户信息Map（只包含需要的字段）
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("userId", loginUser.getSysUser().getUserId());
        userInfo.put("userName", loginUser.getSysUser().getUserName());
        userInfo.put("nickName", loginUser.getSysUser().getNickName());
        userInfo.put("phonenumber", loginUser.getSysUser().getPhonenumber());
        userInfo.put("email", loginUser.getSysUser().getEmail());
        userInfo.put("deptName", loginUser.getSysUser().getDept().getDeptName());
        userInfo.put("roles", loginUser.getRoles());
        userInfo.put("permissions", loginUser.getPermissions());

        resultMap.put("userInfo", userInfo); // 添加用户信息

        // 5. 返回最终封装的结果
        return R.ok(resultMap);
    }
}
